package com.flower.enjoyment.flower.controller;

import com.alibaba.fastjson.JSONObject;
import com.flower.enjoyment.flower.base.ResultMsg;
import com.flower.enjoyment.flower.base.WeChatConfig;
import com.flower.enjoyment.flower.config.WxSPConfig;
import com.flower.enjoyment.flower.entity.UserInfo;
import com.flower.enjoyment.flower.entityDo.UserInfoDo;
import com.flower.enjoyment.flower.enumUtils.ResultEnum;
import com.flower.enjoyment.flower.service.UserInfoService;
import com.flower.enjoyment.flower.utils.AesCbcUtil;
import com.flower.enjoyment.flower.utils.HttpClientUtil;
import com.flower.enjoyment.flower.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/WeChatApi")
@Api(value = "微信登录信息",description = "微信登录用户信息")
public class WeChatLoginController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserInfoService userInfoService;

    /*@ApiOperation(value="用户微信登录授权", notes="用户登录")
    @ResponseBody
    @RequestMapping("/me/login")
    public ResultMsg<UserInfoDo> user_login(HttpServletResponse resp, HttpServletRequest req
    ){
        try {

            resp.setHeader("Access-Control-Allow-Origin", "*");
            resp.setContentType("text/html;charset=UTF-8");

            Enumeration enu=req.getParameterNames();
            while(enu.hasMoreElements()){
                String paraName=(String)enu.nextElement();
                System.out.println("-----------------------"+paraName+": "+req.getParameter(paraName));
            }
            System.out.println("-----------------------");
            String code = req.getParameter("code");
            String userHead = req.getParameter("userHead");
            String userName = req.getParameter("userName");
            String userGender = req.getParameter("userGender");
            String userCity = req.getParameter("userCity");
            String userProvince = req.getParameter("userProvince");
            String sourceUserId = req.getParameter("sourceUserId");
            System.out.println("=============code:" + code + " nickName:" + userName + " userGender:" + userGender);



            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", WeChatConfig.WX_LOGIN_APPID);
            param.put("secret", WeChatConfig.WX_LOGIN_SECRET);
            param.put("js_code", code);
            param.put("grant_type", WeChatConfig.WX_LOGIN_GRANT_TYPE);
            // 发送请求
            String wxResult = HttpClientUtil.doGet(WeChatConfig.WX_LOGIN_URL, param);
            logger.info("授权微信返回结果-----------------------------------------"+wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();

            String open_id = jsonObject.get("openid").toString();
            // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
            UserInfoDo userInfoDo = userInfoService.selectByOpenId(open_id);
            if (userInfoDo != null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setUserHead(userHead);
                userInfo.setUserName(userName);
                if("1".equals(userGender)) {
                    userInfo.setUserGender("男");
                }else if ("2".equals(userGender)){
                    userInfo.setUserGender("女");
                }else{
                    userInfo.setUserGender("未知");
                }
                userInfo.setUserCity(userCity);
                userInfo.setUserProvince(userProvince);
                userInfo.setUserOpenid(open_id);
                userInfo.setIsBoss(0);
                userInfo.setUserNewLogin(new Date());
                //BeanUtils.copyProperties(userInfo, userInfoDo);
                userInfoService.updateById(userInfo);
            } else {
                UserInfo insert_user = new UserInfo();
                insert_user.setId(RandomUtil.getUuid());
                insert_user.setUserHead(userHead);
                insert_user.setUserName(userName);
                if("1".equals(userGender)) {
                    insert_user.setUserGender("男");
                }else if ("2".equals(userGender)){
                    insert_user.setUserGender("女");
                }else{
                    insert_user.setUserGender("未知");
                }
                insert_user.setUserNewLogin(new Date());
                insert_user.setUserCity(userCity);
                insert_user.setUserProvince(userProvince);
                insert_user.setIsBoss(0);
                insert_user.setUserOpenid(open_id);
                insert_user.setSourceUserId(sourceUserId);
                insert_user.setUserNewLogin(new Date());
                // 添加到数据库
                int result= userInfoService.insert(insert_user);
                userInfoDo = userInfoService.selectByOpenId(open_id);
                if (result==0) {
                    return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
                }
            }
            // 封装返回小程序
            Map<String, Object> result = new HashMap<>();
            result.put("session_key", session_key);
            result.put("open_id", open_id);
            result.put("userInfo",userInfoDo);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("微信授权登录出现异常,{1}",e);
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode(), null);
        }

    }*/

    @ApiOperation(value="用户微信登录授权", notes="用户登录")
    @ResponseBody
    @RequestMapping("/me/decodeUser")
    public ResultMsg<UserInfoDo> decodeUser(@ApiParam(value = "用户加密数据") @RequestParam( value = "encryptedData",required = true) String encryptedData,
                                            @ApiParam(value = "加密算法初始常量") @RequestParam( value = "iv",required = true) String iv,
                                            @ApiParam(value = "code") @RequestParam( value = "code",required = true) String code,
                                            @ApiParam(value = "分享人ID") @RequestParam( value = "sourceUserId",required = true) String sourceUserId){
        try {

            logger.info("用户登录信息：code:{};分享人ID:{}",code,sourceUserId);
            if (code == null || code.length() == 0) {
                return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
            }
            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", WeChatConfig.WX_LOGIN_APPID);
            param.put("secret", WxSPConfig.MCH_KEY);
            param.put("js_code", code);
            param.put("grant_type", WeChatConfig.WX_LOGIN_GRANT_TYPE);
            // 发送请求
            String wxResult = HttpClientUtil.doGet(WeChatConfig.WX_LOGIN_URL, param);
            logger.info("授权微信返回结果-----------------------------------------"+wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            logger.info("-----------微信授权后返回数据：{}",jsonObject);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();

            String open_id = jsonObject.get("openid").toString();

            UserInfoDo userInfoDo = userInfoService.selectByOpenId(open_id);
            UserInfo userInfo = new UserInfo();
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            logger.info("解密返回的数据：{}",result);
            if (null != result && result.length() > 0) {
                JSONObject userInfoJSON = JSONObject.parseObject(result);

                userInfo.setUserHead(userInfoJSON.getString("avatarUrl"));
                userInfo.setUserName(userInfoJSON.getString("nickName"));
                if("1".equals(userInfoJSON.get("gender"))) {
                    userInfo.setUserGender("男");
                }else if ("2".equals(userInfoJSON.get("gender"))){
                    userInfo.setUserGender("女");
                }else{
                    userInfo.setUserGender("未知");
                }
                userInfo.setUserCity(userInfoJSON.getString("city"));
                userInfo.setUserProvince(userInfoJSON.getString("province"));
                userInfo.setUserOpenid(open_id);
                userInfo.setUserNewLogin(new Date());
                userInfo.setUserCountry(userInfoJSON.getString("country"));
                userInfo.setUnionId(userInfoJSON.getString("unionId"));


            }else{
                return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
            }
            // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库

            if (userInfoDo != null) {

                userInfo.setId(userInfoDo.getId());
                logger.info("用户登录：{}",userInfo);
                //BeanUtils.copyProperties(userInfo, userInfoDo);
                userInfoService.updateById(userInfo);
            } else {
                userInfo.setId(RandomUtil.getUuid());

                userInfo.setIsBoss(0);
                userInfo.setSourceUserId(sourceUserId);

                userInfo.setUserNewLogin(new Date());
                userInfo.setAmount(0.0);
                userInfo.setGiveAmount(0.0);
                userInfo.setTotalIncome(0.0);
                userInfo.setTodayIncome(0.0);
                userInfo.setIncomeBalance(0.0);
                // 添加到数据库
                int results= userInfoService.insert(userInfo);
                userInfoDo = userInfoService.selectByOpenId(open_id);
                if (results==0) {
                    return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
                }
            }
            // 封装返回小程序
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("session_key", session_key);
            resultMap.put("open_id", open_id);

            resultMap.put("userInfo",userInfoDo);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), resultMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("微信授权登录出现异常,{1}",e);
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode(), null);
        }

    }
}
